#include "stdafx.h"
#include "chat_reply_op.h"
#include <string>
#include <Util/StringUtil.h>
#include <Util/CodeUtil.h>
#include <Util/StringUtil.h>
#include <util/WinAPITools.h>
#include <interface/log_interface.h>
#include <interface/data_op/table_wrapper.h>

namespace aot{ namespace data{

chat_reply_op_impl::chat_reply_op_impl()
{
}

chat_reply_op_impl::~chat_reply_op_impl()
{
}

bool
chat_reply_op_impl::get_all_i(const char* table, aot::tt::ivec_str** out)
{
    aot::tt::vec_str_impl* p = new aot::tt::vec_str_impl();
    *out = (aot::tt::ivec_str*) p;

    std::string sql_exe;
    std::string sql_fmt = "select id, content from %s;";
    sql_exe = aot::tt::utility::StrUtil::Printf(sql_fmt.c_str(), table);
   
    aot::data::table_helper t_table;
    bool ret = g_db_user->exec_and_get_record(sql_exe.c_str(), t_table);

    std::string value;
    for( int i = 0; i < t_table.get_rows_count(); i++ )
    {
        t_table.set_row_index(i);
        value = t_table.get_field_value_str("content");
        p->push_back(value.c_str());
    }
    return ret;
}

bool
chat_reply_op_impl::update_i(const char* table, aot::tt::ivec_str* p)
{

    if( NULL == p )
        return false;

    std::string sql_exe;
    std::string sql_fmt;

    this->begin_transaction();
   
    sql_fmt = "delete from %s;";
    sql_exe = aot::tt::utility::StrUtil::Printf(sql_fmt.c_str(), table);
    g_db_user->exec(sql_exe.c_str()); 

    sql_fmt = "insert into %s (id,content) values(%d, '%s');";
    int i = 1;
    for ( i = 1, p->goto_begin(); !p->is_end(); p->goto_next(), ++i)
    {
        std::string reply_info = p->get_value();
        if( reply_info == "" )
        {
            continue;
        }

        sql_exe = aot::tt::utility::StrUtil::Printf(sql_fmt.c_str(), table, i, reply_info.c_str());
        g_db_user->exec(sql_exe.c_str());
    }
    return this->commit_transaction();
}

bool
chat_reply_op_impl::auto_reply_get_all(aot::tt::ivec_str** out)
{
    return get_all_i("reply_auto", out);
}

bool
chat_reply_op_impl::auto_reply_update(aot::tt::ivec_str* p)
{
    return update_i("reply_auto", p);
}

bool
chat_reply_op_impl::quick_reply_get_all(aot::tt::ivec_str** out)
{
    return get_all_i("reply_quick", out);
}

bool
chat_reply_op_impl::quick_reply_update(aot::tt::ivec_str* p)
{
    return update_i("reply_quick", p);
}

}}